import { useEffect, useState } from "react";
import { Redirect, Route, Switch } from "react-router-dom";

import GlobalContext from "./utils/GlobalContext";
import Manager from "./components/modules/manager/Entry";
import Main from "./components/modules/main/Entry";
import Api from "./utils/api";
import AccountApi from "./utils/apis/AccountApi";
import URIUtil from "./utils/helper/uri";

const nodeEnv = process.env.NODE_ENV
export default function App() {
  const [globalConfig, setGlobalConfig] = useState();
  const [userPermissions, setUserPermissions] = useState([]); // 状态存储用户权限
  const [cacheDatas, setCacheDatas] = useState({});

  useEffect(() => {
    Api.getConfig().then(config => {
      if (nodeEnv !== "development") {
        AccountApi.userInfo().then(resp => {
          console.log("用户信息", resp);

          if (resp.code === 302 && resp.data) {
            // const params = URIUtil.parseParams(resp.data)
            // const serviceUrl = decodeURIComponent(params.service)
            // const serviceParams = URIUtil.parseParams(serviceUrl)
            // serviceParams.redirect = window.location.href
            // const newServiceUrl = URIUtil.appendParams(serviceUrl.split('?')?.[0], serviceParams)
            const serviceUrl = `${window.location.origin}/admin-api/casLogin?redirect=${window.location.href}`
            // const newUrl = `${resp.data.split('?')?.[0]}?service=${encodeURIComponent(serviceUrl)}`
            const newUrl = `${resp.data}`
            //console.log(newUrl);
            // debugger
            window.location.href = newUrl;
          } else {
            window.userAreaCode = resp.data?.user?.areaCode?.length === 6 ? (resp.data?.user?.areaCode.endsWith("00") ? null : resp.data?.user?.areaCode) : null;
            setGlobalConfig({
              ...config,
              userInfo: resp.data
            });
          }
        })
      } else {
        // window.userAreaCode = '511526'
        setGlobalConfig(config)
      }
    })
  }, [])

  // 权限受限的路径
  const restrictedPath = "/main/jcyj/dzjc";

  return (
    globalConfig ? <GlobalContext.Provider value={{
      ...globalConfig,
      setGlobalConfig,
      userPermissions,
      setUserPermissions,
      cacheDatas,
      setCacheDatas
    }}>
      <Switch>

        <Redirect exact path="/" to={"/main"}></Redirect>
        {/* <Redirect path="/home" to={"/main/home"}></Redirect> */}
        <Route path="/manager" component={Manager}></Route>
        <Route path="/main" component={Main}></Route>

        {/* <Route exact path="/login" component={Login}></Route> */}
      </Switch>
    </GlobalContext.Provider> : null
  );
}
